﻿using UnityEngine;

public class WaitServerMgr : IZUpdate
{
    private Transform trans;
    private float viewTime;
    private float curTime;

    private bool lockScreen;            //是否出现等待消息锁屏
    private float lockDelayTime;        //锁屏出现需求等待时间 (秒)
    private float lockScreenTimer;      //当前计时（秒）

    private bool isOpening;             // waitserver界面是否是打开状态
    private bool isImmediate;

    public WaitServerMgr()
    {
        trans = AllUpdate.GetChildByName("WaitServer");
        Utility.SetActive(trans, false);

        UpdateMgr.GetSingleton().AddUpdate(this);
        lockDelayTime = DBSystemMgr.GetSingleton().GetGlobalFloat(2);
        viewTime = DBSystemMgr.GetSingleton().GetGlobalFloat(3);
        isOpening = false;
    }

    public void Open()
    {
        UpdateMgr.GetSingleton().AddUpdate(this);
        curTime = 0; isOpening = true;
        Utility.SetActive(trans, isOpening);
    }

    public void Close()
    {
        UpdateMgr.GetSingleton().RemoveUpdate(this);
        curTime = 0; isOpening = false;
        Utility.SetActive(trans, isOpening);
    }
    
    public void StartWait(int id)
    {
        if (!lockScreen)
        {
            EDebug.Log("等待服务器计时开始" + id.ToString());
            lockScreen = true;
            lockScreenTimer = 0;
        }
    }

    public void StartWait(string info, bool isImmediate = false)
    {
        if (!lockScreen)
        {
            EDebug.Log("等待服务器计时开始" + info);
            lockScreen = true;
            lockScreenTimer = 0;
            this.isImmediate = isImmediate;
        }
        ZUpdate();
    }

    public void EndWait(int id)
    {
        if (lockScreen)
        {
            EDebug.Log("等待服务器计时停止" + id.ToString());
            lockScreen = false;
            lockScreenTimer = 0;
            Close();
        }
    }

    public void EndWait(string info)
    {
        if (lockScreen)
        {
            EDebug.Log("等待服务器计时停止" + info);
            lockScreen = false;
            lockScreenTimer = 0;
            Close();
        }
    }

    public void ZUpdate()
    {
        if (lockScreen && !isOpening)
        {
            lockScreenTimer += Time.deltaTime;
            if (lockScreenTimer >= lockDelayTime || isImmediate)
            {
                EDebug.Log("打开waitserver界面!");
                lockScreenTimer = 0;
                isImmediate = false;
                Open();
            }
        }
        else
        {
            curTime += Time.deltaTime;
            if (curTime >= viewTime)
            {
                EDebug.Log("关闭waitserver界面!");
                GameClient.GetSingleton().OnDisconnect();
                Close();
            }
        }
    }
}